import {Component, OnInit, EventEmitter, Input, Output} from '@angular/core';
import {zh_CN, NzI18nService} from 'ng-zorro-antd';
import * as differenceInCalendarDays from 'date-fns/difference_in_calendar_days';
import {fadeIn} from "../../../../animate";
import {RollService} from "../../../../my-service/roll.service";
import {NzMessageService} from 'ng-zorro-antd';
import {UtilService} from "../../../../my-service/util.service";

declare let $: any;

@Component({
  selector: 'app-add-roll',
  templateUrl: './add-roll.component.html',
  styleUrls: ['./add-roll.component.css'],
  animations: [fadeIn]
})
export class AddRollComponent implements OnInit {
  @Output() onCloseAdd = new EventEmitter<boolean>();
  @Input() updateRoll: object;
  @Input() userGuid: string;
  dateFormat = 'yyyy/MM/dd';
  readImgUrl: string = null;
  today = new Date();
  selectDateStyle = {
    width: '414px',
    height: '36px',
    lineHeight: '36px',
    color: '#fff'
  };
  addRoll = {
    title: '',
    userGuid: '',
    titleSize: 0,
    endTime: new Date(),
    addEndTimeMon: 3,//到期时间默认为当前日期之后的3个月
    rollCode: null,
    rollCodeLength: 5,//邀请码长度
    coverGrey: true,
    closeAddRoll: false,//关闭这个组件
    isUpdate: false,//修改还是添加
    coverUrl: '', /*封面图片地址*/
    coverArr: [],
    coverGreyArr: [true, true, true, true], /*控制单个鼠标移入移出效果*/
    updateRoll: {},
    isLoading: false,//是否显示加载框
    addStatus: 0,//防止多次点击进行重复提交
    that: null,
    getEndTime: function (time) {
      this.endTime = time;
      console.log(this.endTime);
    },//结束时间获取
    getDefaultCover: function (i) {
      this.that.isDeleteImg();
      this.coverUrl = this.coverArr[i];
      this.coverGrey = false;
    },//默认封面替换
    hoverChangeGrey: function (i, f) {
      this.coverGreyArr[i] = f;
    },//输入表移入提出改变cover灰度
    createCode: function () {
      this.rollCode = (Math.random() * Date.now() / 100000).toFixed(0);
      if (this.rollCode.length > this.rollCodeLength) {
        this.rollCode = this.rollCode.toString().slice(this.rollCode.length - this.rollCodeLength);
      } else if (this.rollCode.length < this.rollCodeLength) {
        for (let i = 0; i < this.rollCodeLength - this.rollCode.length; i++) {
          this.rollCode = '' + i;
        }
      }
    },//随机生成6位邀请码
    uploadRoll: function () {
      let endTime = new Date(this.endTime).getFullYear() + '-' + (new Date(this.endTime).getMonth() + 1) + '-' + new Date(this.endTime).getDate();
      if (this.isUpdate) {
        return {
          className: this.title,
          inviteCode: this.rollCode,
          endTime: endTime,
          creatorGuid: this.userGuid,
          coverUrl: this.coverUrl,
          PK_ClassGuid: this.updateRoll.PK_ClassGuid
        }
      } else {
        return {
          className: this.title,
          inviteCode: this.rollCode,
          endTime: endTime,
          creatorGuid: this.userGuid,
          coverUrl: this.coverUrl
        }
      }

    },//返回上传需要的数据
    _constructor: function () {
      this.isUpdate = true;
      this.title = this.updateRoll.ClassName;
      this.rollCode = this.updateRoll.InvitationCode;
      this.endTime = new Date(this.updateRoll.EndTime.replace(/-/g, "/"));
      this.coverUrl = this.updateRoll.CoverUrl;
    }
  };

  /*addRoll参数提示
  * */
  constructor(private nzI18nService: NzI18nService, private rollServe: RollService, private message: NzMessageService, private utileServe: UtilService) {
    this.readImgUrl = this.utileServe.readImgUrl;
  }

  getDefaultCover(): void {
    this.rollServe.getDefaultCover().then(res => {
      if (res.status == 1) {
        this.addRoll.coverArr = res.data;
      } else {
        console.log(res);
      }
    })
  }

  deleteImg(url): void {
    this.rollServe.deleteIMG(url).then(res => {
    })
  }

  isDeleteImg() {
    if (this.addRoll.coverUrl) {
      if (this.addRoll.coverArr.some((item) => {
          return this.addRoll.coverUrl == item
        })) {
      } else {
        this.deleteImg(this.addRoll.coverUrl);
      }
    }
  }

  /*判断是否需要删除封面*/
  ngOnInit() {
    this.nzI18nService.setLocale(zh_CN);
    this.addRoll.that = this;
    this.addRoll.userGuid = this.userGuid;
    this.addRoll.endTime.setMonth(this.addRoll.endTime.getMonth() + this.addRoll.addEndTimeMon);
    this.getDefaultCover();
    if (this.updateRoll) {
      this.addRoll.updateRoll = this.updateRoll;
      this.addRoll._constructor();
    }
  }

  onClose(status) {
    //1表示正常关闭，0表示不正常关闭
    if (!this.addRoll.isUpdate&&status==0) {
      this.isDeleteImg();
    }
    //关闭按钮时如果用户上传了图片，先删除图片
    this.updateRoll = null;
    this.addRoll.updateRoll = null;
    this.onCloseAdd.emit(this.addRoll.closeAddRoll);
  }

  disabledDate = (current: Date): boolean => {
    // 控制日期可选
    return differenceInCalendarDays(current, this.today) < 0;
  };

  uploadCover($event) {
    const fileReader = new FileReader();
    const file = $event.target.files[0];
    if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
      this.addRoll.isLoading = false;
      this.message.error('封面上传失败，封面类型应该为jpeg或者png');
      return;
    }
    if (file.size > 2097152) {
      this.addRoll.isLoading = false;
      this.message.error('封面上传失败，封面图片大小请限制在2M以内');
      return;
    }
    this.isDeleteImg();
    let that = this;
    fileReader.onload = function ($event) {
      that.addRoll.isLoading = true;
      $('.upload-class').ajaxSubmit({
        url: that.utileServe.loodImgUrl + `/?directory=Roster/Roster/cover&userGuid=${that.addRoll.userGuid}`,
        type: 'post',
        success: function (data) {
          if (data) {
            that.addRoll.isLoading = false;
            that.addRoll.coverUrl = data;
            that.message.success('花名册封面上传成功');
          }
          /*对网路图片地址进行拼装*/
        },
        error: function () {
          that.addRoll.isLoading = false;
          that.message.error('图片上传失败，请重试');
        }
      });
    };
    fileReader.readAsDataURL(file);
  }

  /*将添加比赛页面的封面图片上传并进行预览*/
  uploadAddRoll() {
    if (this.addRoll.addStatus !== 0) {
      return;
    }
    let data = this.addRoll.uploadRoll();
    if (!data.className) {
      this.message.warning('花名册名称不能为空');
      return
    } else if (!data.coverUrl) {
      this.message.warning('请选择默认封面或者上传封面');
      return
    } else if (!data.endTime) {
      this.message.warning('请选择到期时间');
      return
    } else if (!data.inviteCode) {
      this.message.warning('请输入邀请码或者随机生成邀请码');
      return
    } else if (isNaN(data.inviteCode)) {
      this.message.warning(`邀请码应该为纯数字`);
      return
    }
    else if (data.inviteCode.length < this.addRoll.rollCodeLength) {
      this.message.warning(`您输入的邀请码不足${this.addRoll.rollCodeLength}位数字`);
      return
    }
    this.addRoll.addStatus++;
    if (this.addRoll.isUpdate) {
      this.rollServe.upDateRoll(data).then(res => {
        if (res.status == 1) {
          this.message.success('花名册修改成功');
          this.onClose(1);
        } else {
          console.log(res);
          this.message.error('服务器内部错误，请刷新重试');
        }
      })
    } else {
      this.rollServe.uploadRoll(data).then(res => {
        if (res.status == 1) {
          this.message.success('花名册创建成功');
          this.onClose(1);
        } else {
          console.log(res);
          this.message.error('服务器内部错误，请刷新重试');
        }
      })
    }

  }
}
